package net.melon.product.inst.service.impl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.esj.basic.core.view.tools.ActionContext;
import net.esj.basic.dao.querybuilder.QueryBuilder;
import net.esj.basic.exception.MelonRuntimeException;
import net.esj.basic.service.impl.DefaultServiceImpl;
import net.esj.basic.utils.Assert;
import net.melon.product.inst.service.BrandService;
import net.melon.product.pojo.ProductBrand;
import net.melon.uploader.Uploader;
import net.melon.uploader.pojo.FileUpload;
import net.melon.uploader.service.impl.DateSplitPathRule;
import net.melon.uploader.service.impl.RandomFileNameRule;

import org.springframework.stereotype.Service;

@Service("brandService")
public class BrandServiceImpl extends DefaultServiceImpl implements BrandService {
	
	@Override
	public void addBrand(ProductBrand brand) {
		try {
			Uploader uploader = new Uploader(new DateSplitPathRule(), new RandomFileNameRule(), ProductBrand.ICON_SUB_DIR);
			uploader.setAllowFiles(Uploader.ALLOW_FILE_IMAGES);
			List<FileUpload> list = uploader.upload((HttpServletRequest)ActionContext.getRequest());
			if(!list.isEmpty()){
				FileUpload up = list.get(0);
				brand.setIcon(up.getUrl());
			}
		} catch (Exception e) {
			throw new MelonRuntimeException(e);
		}
		brand.setState(1);
		save(brand);
	}

	@Override
	public void updateBrand(ProductBrand brand) {
		try {
			Uploader uploader = new Uploader(new DateSplitPathRule(), new RandomFileNameRule(), ProductBrand.ICON_SUB_DIR);
			uploader.setAllowFiles(Uploader.ALLOW_FILE_IMAGES);
			List<FileUpload> list = uploader.upload((HttpServletRequest)ActionContext.getRequest());
			if(!list.isEmpty()){
				FileUpload up = list.get(0);
				brand.setIcon(up.getUrl());
			}
		} catch (Exception e) {
			throw new MelonRuntimeException(e);
		}
		update(brand);
	}

	@Override
	public void deleteBrand(Long id) {
		ProductBrand brand = get(id, ProductBrand.class);
		Assert.notNull(brand);
		brand.setState(-1);
		update(brand);
	}

	@Override
	public List<ProductBrand> brandList() {
		QueryBuilder<ProductBrand> qb = createQueryBuilder(ProductBrand.class);
		qb.eq("state", 1);
		return queryListByQueryBuilder(qb);
	}

}
